package com.ruoyi.course.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.course.domain.LabCourse;
import com.ruoyi.course.domain.LabCourseDate;
import com.ruoyi.course.domain.LabCourseTimetable;
import com.ruoyi.course.dto.CourseDto;
import com.ruoyi.course.dto.CourseTable;
import com.ruoyi.course.service.ILabCourseDateService;
import com.ruoyi.course.service.ILabCourseService;
import com.ruoyi.course.service.ILabCourseTimetableService;
import com.ruoyi.system.utils.SysDateUtils;

/**
 * 课程管理Controller
 * 
 * @author jun.wang
 * @date 2022-04-09
 */
@RestController
@RequestMapping("/course/course")
public class LabCourseController extends BaseController {
	private static final Logger log = LoggerFactory.getLogger(LabCourseController.class);
	@Autowired
	private ILabCourseService labCourseService;
	@Autowired
	private ILabCourseDateService labCourseDateService;
	
	@Autowired
	private ILabCourseTimetableService labCourseTimetableService;

	/**
	 * 查询课程管理列表
	 */
	@PreAuthorize("@ss.hasPermi('course:course:query')")
	@GetMapping("/list")
	public TableDataInfo list(LabCourse labCourse) {
		startPage();
		List<LabCourse> list = labCourseService.selectLabCourseList(labCourse);
		return getDataTable(list);
	}
	
	/**
	 * 查询某周某个实验室的课表
	 */
	@PreAuthorize("@ss.hasPermi('course:course:query')")
	@GetMapping("/getWeekTable")
	public AjaxResult getWeekTable(LabCourseDate labCourseDate) {
		//没有选择实验室，直接返回空数据
		if(labCourseDate.getLabId()==null){
			return AjaxResult.success();
		}
		
		LabCourseTimetable timeTable = null;
		if(labCourseDate.getTimetableId()==null){
			timeTable =  labCourseTimetableService.getDefaultTimetable(new Date());
			if(timeTable==null){
				return AjaxResult.success();
			}else{
				labCourseDate.setTimetableId(timeTable.getTimetableId());
			}
		}else{
			timeTable = labCourseTimetableService.selectLabCourseTimetableById(labCourseDate.getTimetableId());
		}
		if(labCourseDate.getWeekNum()==null){
			labCourseDate.setWeekNum(SysDateUtils.getCourseWeekNum(timeTable.getCourseStartDate(), new Date()));
		}
		List<LabCourseDate> labCourseDateList = labCourseDateService.selectLabCourseDateList(labCourseDate);
		List<CourseTable> courseTableList = new ArrayList<CourseTable>();
		for(int i=1; i<=12;i++){
			CourseTable course = new CourseTable();
			course.setWeekNum(labCourseDate.getWeekNum());
			course.setTimetableId(labCourseDate.getTimetableId());
			course.setSectionName(i+"");
			courseTableList.add(course);
		}
		courseTableList.get(0).setDayList(SysDateUtils.getCourseWeekNumDate(timeTable.getCourseStartDate(), labCourseDate.getWeekNum()));
		for(LabCourseDate item : labCourseDateList){
			
			List<Integer> sectionArr = new ArrayList<Integer>();
			if(item.getSectionStart()!=null){
				sectionArr.add(item.getSectionStart());
				if(item.getSectionEnd()!=null){
					for(int k = item.getSectionStart()+1 ;k<=item.getSectionEnd();k++){
						sectionArr.add(k);
					}
				}
			}else if(item.getRemark()!=null){
				String remark = item.getRemark().replace("节", "");
				String[] sections = remark.split(",");
				for(int j=0;j<sections.length; j++){
					sectionArr.add(Integer.valueOf(sections[j]));
				}
			}else{
				log.warn("节次数据不完整或输入错误,课表展示会缺少");
				continue;
			}
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(item.getCourseDate());
			int weekDay = calendar.get(Calendar.DAY_OF_WEEK) - 1;
			if(weekDay==0){
				weekDay = 7;
			}
			for(Integer section : sectionArr){
				CourseTable course  = courseTableList.get(section - 1);
				switch(weekDay){
						case 1:  //day1
							course.setDay1(item);
							break;
						case 2: //day2
							course.setDay2(item);
							break;
						case 3: //day3
							course.setDay3(item);
							break;
						case 4:
							course.setDay4(item);
							break;
						case 5:
							course.setDay5(item);
							break;
						case 6:
							course.setDay6(item);
							break;
						case 7:
							course.setDay7(item);
							break;
						default:
				}
			}
		
		}
		
		return AjaxResult.success(courseTableList);
	}

	/**
	 * 查询课程管理列表
	 */
	@PreAuthorize("@ss.hasPermi('course:course:query')")
	@GetMapping("/dateList")
	public TableDataInfo dateList(LabCourse labCourse) {
		startPage();
		List<LabCourse> list = labCourseService.selectLabCourseDateList(labCourse);
		return getDataTable(list);
	}
	
	/**
	 * 修改课程管理
	 */
	//@PreAuthorize("@ss.hasPermi('course:course:edit')")
	@Log(title = "课程同步", businessType = BusinessType.INSERT)
	@GetMapping("/synchCourse")
	public AjaxResult synchCourseData(Long timetableId) {
		return toAjax(labCourseService.synchCourseData(timetableId));
	}

	/**
	 * 导出课程管理列表
	 */
	// @PreAuthorize("@ss.hasPermi('course:course:export')")
	// @Log(title = "课程管理", businessType = BusinessType.EXPORT)
	/*
	 * @GetMapping("/export") public AjaxResult export(LabCourse labCourse) {
	 * List<LabCourse> list = labCourseService.selectLabCourseList(labCourse);
	 * ExcelUtil<LabCourse> util = new ExcelUtil<LabCourse>(LabCourse.class);
	 * return util.exportExcel(list, "course"); }
	 */

	/**
	 * 获取课程管理详细信息
	 */
	@PreAuthorize("@ss.hasPermi('course:course:query')")
	@GetMapping(value = "/{courseId}")
	public AjaxResult getInfo(@PathVariable("courseId") Long courseId) {
		return AjaxResult.success(labCourseService.selectLabCourseById(courseId));
	}

	/**
	 * 新增课程管理
	 */
	@PreAuthorize("@ss.hasPermi('course:course:edit')")
	@Log(title = "课程管理", businessType = BusinessType.INSERT)
	@PostMapping
	public AjaxResult add(@RequestBody LabCourse labCourse) {
		return toAjax(labCourseService.insertLabCourse(labCourse));
	}

	/**
	 * 修改课程管理
	 */
	@PreAuthorize("@ss.hasPermi('course:course:edit')")
	@Log(title = "课程管理", businessType = BusinessType.UPDATE)
	@PutMapping
	public AjaxResult edit(@RequestBody LabCourse labCourse) {
		return toAjax(labCourseService.updateLabCourse(labCourse));
	}

	/**
	 * 删除课程管理
	 */
	@PreAuthorize("@ss.hasPermi('course:course:edit')")
	@Log(title = "课程管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{courseIds}")
	public AjaxResult remove(@PathVariable Long[] courseIds) {
		return toAjax(labCourseService.deleteLabCourseByIds(courseIds));
	}

	@GetMapping("/list/week")
	public TableDataInfo listWeek(LabCourse labCourse) {
		// startPage();
		List<LabCourse> list = labCourseService.selectLabCourseWeekList(labCourse);
		return getDataTable(list);
	}

	@GetMapping("/list/month")
	public TableDataInfo listMonth(LabCourse labCourse) {
		// startPage();
		List<LabCourse> list = labCourseService.selectLabCourseMonthList(labCourse);
		return getDataTable(list);
	}

	/**
	 * 删除课程管理
	 */
	@PreAuthorize("@ss.hasPermi('course:course:edit')")
	@Log(title = "课程管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/date/{courseDateId}")
	public AjaxResult remove(@PathVariable Long courseDateId) {
		return toAjax(labCourseService.deleteLabCourseDateById(courseDateId));
	}

	/**
	 * 获取课程管理详细信息
	 */
	@PreAuthorize("@ss.hasPermi('course:course:query')")
	@GetMapping(value = "/date/{courseDateId}")
	public AjaxResult getCourseDateInfo(@PathVariable("courseDateId") Long courseDateId) {
		return AjaxResult.success(labCourseService.selectLabCourseDateById(courseDateId));
	}

	@PostMapping("/importData")
	public AjaxResult importData(MultipartFile file) throws Exception
	{
		String originalFilename = file.getOriginalFilename();
		ExcelUtil<CourseDto> util = new ExcelUtil<CourseDto>(CourseDto.class);
		List<CourseDto> courseDtos = util.importExcel(file.getInputStream());
		labCourseService.importData(courseDtos, originalFilename);
		return AjaxResult.success("导入成功");
	}

	@GetMapping("/importTemplate")
	public void importTemplate(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		// 下载名称
		response.setCharacterEncoding("utf-8");
		response.setContentType("multipart/form-data");
		response.setHeader("Content-Disposition",
				"attachment;fileName=" + FileUtils.setFileDownloadHeader(request, "课程导入模板.xlsx"));
		InputStream resourceAsStream = LabCourseController.class.getClassLoader().getResourceAsStream("imp_template/课程导入模板.xlsx");
		IOUtils.copy(resourceAsStream, response.getOutputStream());
	}
}
